package pe.edu.unmsm.fisi.sysllabus.presentacion.controller.login;

import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Scope;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.security.ui.WebAuthenticationDetails;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;
import org.springframework.stereotype.Controller;

import pe.edu.unmsm.fisi.sysllabus.negocio.modelo.dto.UsuarioDTO;
import pe.edu.unmsm.fisi.sysllabus.negocio.servicio.UsuarioService;

@Controller
@Scope("session")
public class LoginController {

	/*****************ATRIBUTOS**************/
	private UsuarioDTO usuario;
	private boolean permisoadmin;
	private boolean permisodoc;
	private boolean permisodel;
	private String dirMenu;
	
	@Resource
	UsuarioService usuServ;
	
	@Resource(name="MyAuthenticationManager")
	private AuthenticationManager authenticationManager;
	/*****************INICIALIZACION**************/
	public LoginController() {
		setUsuario(new UsuarioDTO());
	}
	
	/*****************NAVEGACION**************/
	public void cerrarSesion(ActionEvent event)throws Exception{
		String out=cerrarSesionGeneric();
	}

	public String cerrarSesionGeneric() {
		try {
			HttpSession se2=(HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	    	se2.invalidate();			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "error";
	}
	
	public String iraProcIniCronograma(){
		return "procIniCrono";
	}
	
	public String iraManteCarrera(){
		return "mantCarrera";
	}
	
	public String iraEnvModifSyllabus(){
		return "modSyllabus";
	}
	
	public String iraValidarAvanSyllabus(){
		return "valavasyl";
	}
	
	public String iraGestAvanSyllabus(){
		return "gestavsyl";
	}
	
	public String iraManteUsu(){
		return "manteUsu";
	}
	
	public String iraRegAvanceSyll(){
		return "avanceSyll";
	}
	public String iraReportes(){
		return "reportes";
	}
	public String iraRegAvanCursos(){
		return "avancesCurso";
	}
	
	public String loginActionAdmin() throws Exception
	{
		try{
			Authentication aut=validarContextSecurity(usuario.getNickname(), usuario.getPassword());
	    	if(aut.isAuthenticated()){	    		
	    		setUsuario(usuServ.obtenerUsuarioxNik(usuario.getNickname()));
	    		setDirMenu(usuServ.obtenerMenuxPerfil(getUsuario().getTipo()));
	    		HttpSession session=(HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
				session.setAttribute("usuarioLogueado", usuario);
	    		return getUsuario().getTipo()+"";
	    	}else {
	    		return "error";
			}
		}catch(AuthenticationException e){
			return "error";	}
	}
	
	public Authentication validarContextSecurity(String usu, String pas)
	{
		HttpServletRequest request= getRequest();
		UsernamePasswordAuthenticationToken authReq=new UsernamePasswordAuthenticationToken(usu, pas);
    	authReq.setDetails(new WebAuthenticationDetails(request));			    	
    	HttpSession session = request.getSession();

    	session.setAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY, usu);
    	Authentication auth = getAuthenticationManager().authenticate(authReq);
        
    	SecurityContext secCtx = SecurityContextHolder.getContext();	    	
    	secCtx.setAuthentication(auth);
    	session.setAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY, secCtx);   			    	

    	String urlKey = AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY;	   
    	//SavedRequest savedRequest = (SavedRequest)session.getAttribute(urlKey);
    	session.removeAttribute(urlKey);
    	return auth ;
	}
	
	private HttpServletRequest getRequest() {
		return (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
	}
	/*****************GETTERS AND SETTERS**************/
	public UsuarioDTO getUsuario() {
		return usuario;
	}

	public void setUsuario(UsuarioDTO usuario) {
		this.usuario = usuario;
	}

	public boolean isPermisodel() {
		return permisodel;
	}

	public void setPermisodel(boolean permisodel) {
		this.permisodel = permisodel;
	}

	public boolean isPermisodoc() {
		return permisodoc;
	}

	public void setPermisodoc(boolean permisodoc) {
		this.permisodoc = permisodoc;
	}

	public boolean isPermisoadmin() {
		return permisoadmin;
	}

	public void setPermisoadmin(boolean permisoadmin) {
		this.permisoadmin = permisoadmin;
	}

	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

	public String getDirMenu() {
		return dirMenu;
	}

	public void setDirMenu(String dirMenu) {
		this.dirMenu = dirMenu;
	}

}
